/**
 * Created by lee_mxue on 17/5/11.
 */
import React from "react";
import ReactDOM from "react-dom";
import AJAX from "../../lib/ajax";
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare";
import Loading from "../../components/Loading/Loading"
import tools from "../../lib/tools";
require('../../lib/rem');
require('./CabinetOpening.less');
require('../../styles/common.less');
require('../../styles/resetWeui.less');
require('../../styles/lux.less')
const Toast = require('../MyPackage/components/Toast')
const Dialog = require('../MyPackage/components/Dialog')
const Pay = require('../MyPackage/components/Pay')

//获取柜体编码
var cabinet_code = tools.getParams().cabinet_code;
//获取订单id
var order_id = tools.getParams().order_id;
//获取开箱参数
var open_cabinetInfo_x = JSON.parse(window.localStorage.getItem("open_cabinetInfo_x"))
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isReady: false,     //是否可以加载页面
            loading: false,
            openedCabinetCellName: undefined,  //已开格口名称
            openedCabinetCellId: undefined,  //已开格口id
            price: undefined,   //已开格口资费
            pay_data: {},   //支付数据
            pay_params: {
                yue_show: false,     //是否显示余额支付，柜体寄件不显示
                type: 3,    //运单类型（1:国内 3:柜体）,默认1
                order_id: order_id,  //订单id
                real_fee: 0,  //支付金额(订单实际金额)
                coupon_reason_id: 0,    //调价原因ID(type为1时必选)
                coupon_remark: '',    //调价原因描述(type为1时必选)
                callback: function () {
                }
            },   //支付参数
        }
        this.jumpToPay = this.jumpToPay.bind(this)  //去支付
    }

    checkPayStaus() {
        return new Promise((resolve, reject) => {
            AJAX.request('query_wx', {
                type: 3,    //运单类型（1:国内 3:柜体）,默认1
                order_id: order_id,  //订单id
            }, function (data) {
                if (data.code == 0) {
                    if (data.body.trade_status == 13103) {
                        //支付成功
                        resolve();
                    }
                }
                reject(data);
            })
        })
    }

    //查询微信支付结果
    handleCheckPayStatus() {
        this.showLoading(true);
        tools.tryAtMost(10, 10, this.checkPayStaus, {}).then(() => {
            this.showLoading(false);
            Dialog.info({
                title: "",
                content: "本次快递费用已支付成功！您可以在个人中心查看订单状态。",
                okText: "知道了",
                onOK: () => {
                    const wx_type = window.localStorage.getItem('wx_type');
                    window.location.href = `./PickUp?wx_type=${wx_type}`;   //返回首页
                }
            })
        }).catch(e => {
            this.showLoading(false);
            Dialog.info({
                title: "",
                content: "已经支付成功，不要再重复支付！您可以在个人中心查看订单状态。",
                okText: "知道了",
                onOK: () => {
                    const wx_type = window.localStorage.getItem('wx_type');
                    window.location.href = `./PickUp?wx_type=${wx_type}`;   //返回首页
                }
            })
        })
    }

    componentWillMount() {
        var _this = this;
        //请求中－－－等待
        addErrorListener()()
        //隐藏分享功能
        weixinShare.hideAll();
        //获取订单支付费用
        var fee = tools.getParams().fee;

        if (open_cabinetInfo_x) {
            //发起开箱请求
            AJAX.request("order_open_cell", open_cabinetInfo_x,
                data => {
                    if (data.code == 0) {
                        this.setState({
                            openedCabinetCellName: data.body.cell_desc,
                            openedCabinetCellId: data.body.cell_id,
                            isReady: true,     //是否可以加载页面
                        })
                        //开箱成功时： 关闭等待状态，打开确认弹窗
                        this.confirm(data.body.cell_desc)
                    } else {
                        //开箱失败提示
                        Dialog.info({
                            title: "",
                            content: data.msg,
                            okText: "知道了",
                            onOK: () => {
                                const wx_type = window.localStorage.getItem('wx_type');
                                window.location.href = `./PickUp?wx_type=${wx_type}`;   //返回首页
                            }
                        })
                    }

                }
            )
        } else if (fee) {
            _this.setState({
                isReady: true,     //是否可以加载页面
                pay_params: {
                    yue_show: false,     //是否显示余额支付，柜体寄件不显示
                    type: 3,    //运单类型（1:国内 3:柜体）,默认1
                    order_id: order_id,  //订单id
                    real_fee: fee,  //支付金额(订单实际金额)
                    coupon_reason_id: 0,    //调价原因ID(type为1时必选)
                    coupon_remark: '',    //调价原因描述(type为1时必选)
                    callback: function () {
                        _this.handleCheckPayStatus()
                    }
                }
            })
        }
    }


    componentDidMount() {
        AJAX.appendBaiduAnalysis()

        //监听手动返回
        var state = {
            title: "title",
            url: "#"
        };
        window.history.pushState(state, "title", "#");
        window.addEventListener("popstate", function (e) {
            window.location.href = './ChooseCabinetType?cabinet_code=' + cabinet_code + '&order_id=' + order_id
            // alert("我监听到了浏览器的返回按钮事件啦");//根据自己的需求实现自己的功能
        }, false)

    }

    //组件卸载，解绑监听事件
    componentWillUnmount() {
        //监听手动返回---解除监听
        window.removeEventListener("popstate", function (e) {
            window.location.href = './ChooseCabinetType?cabinet_code=' + cabinet_code + '&order_id=' + order_id
            // alert("我监听到了浏览器的返回按钮事件啦");//根据自己的需求实现自己的功能
        }, false)
    }

    showLoading(value) {
        this.setState({
            loading: value,
        })
    }

    //toast弹窗
    warn(content) {
        Toast.warn({
            content: content
        })
    }

    success() {
        Toast.success({
            content: "成功"
        })
    }

    error() {
        Toast.error({
            content: "失败"
        })
    }

    //箱门关闭确认弹窗
    confirm(content) {
        var closeParams = {
            order_id: order_id, //订单id
            cabinet_code: cabinet_code, //柜体编号
            cell_id: this.state.openedCabinetCellId,    //格口id
        }
        var _this = this;
        Dialog.confirm({
            title: '',
            content: content + "箱门已开,请在放入快递之后关闭箱门",
            okText: "确认关箱",
            cancelText: "重选格口",
            onOK: () => {
                //  确认投递
                AJAX.request("confirm_delivery", closeParams, data => {
                    if (data.code == 0) {
                        // _this.success();
                        _this.setState({
                            pay_params: {
                                yue_show: false,     //是否显示余额支付，柜体寄件不显示
                                type: 3,    //运单类型（1:国内 3:柜体）,默认1
                                order_id: order_id,  //订单id
                                real_fee: data.body.fee,  //支付金额(订单实际金额)
                                coupon_reason_id: 0,    //调价原因ID(type为1时必选)
                                coupon_remark: '',    //调价原因描述(type为1时必选)
                                callback: function () {
                                    _this.handleCheckPayStatus()
                                }
                            }
                        })
                    }

                })
            },
            onCancel: () => {
                window.location.href = './ChooseCabinetType?cabinet_code=' + cabinet_code + '&order_id=' + order_id + '&is_reselect=1'
            }
        })
    }

    //跳转支付页面
    jumpToPay(state, order_id, out_time) {
        //pay_immediately = true 立即支付
        // window.location.href = './MyPackageRecipentDetail?order_id=${order_id}&out_time=${out_time}&pay_immediately＝'+true
    }

    render() {
        const { loading } = this.state;
        return (
            this.state.isReady &&
            <div className="main">
                <div className="center_content">
                    <div className="img_box">
                        <img src="http://cdn.jinlb.cn/pic/bb/61/bb61c5c2e21d8b3b45d18e5ace96d8aa.jpg" alt="" />
                    </div>
                    <div className="text_box">
                        <p>请在格口中放入包裹后将箱门关闭</p>
                        <p>请在关箱门后完成支付</p>
                    </div>
                </div>
                <div className="bottom_submit">

                    <Pay dataSource={this.state.pay_params} />
                </div>
                <Loading show={loading} text="支付中..." />
            </div>
        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}